var Room = require('./room');
var PlayerManager = require('./playerManager');

var utils = require('../../util/utils');

var log = console.log;

var exp = module.exports;

var roomData = {};  // 保存room实例 {roomId: {room}}
var roomNum = 0;  // room 的总数量

/**
 * 用户进入游戏
 * in: msg: {serverId, playerId, token, gameId, playerName, isRobot, ip}
 */
exp.enterGame = function (msg, cb) {
    if (roomNum <= 0) {
        roomData[++roomNum] = new Room(msg.gameId, roomNum); // gameId, roomId
    }

    roomData[roomNum].addPlayer(msg, function (err, roomId) {
        if (!err) {
            var gameData = roomData[roomId].getGameStatus();
            var playerData = roomData[roomId].getPlayerData(msg.playerId);
            var playerList = roomData[roomId].getPlayerList();
            var banker = roomData[roomId].getCurBankerData();
            var bankerList = roomData[roomId].getBankerList();

            // 房间设置
            var roomSet = { bankerMinCoin: 5000 };

            if (gameData.gameStatus === 3) {
                gameData.cards = roomData[roomId].curResult;
            }

            var ret = {
                gameId: msg.gameId,
                roomId: roomId,
                gameData: gameData,
                playerData: playerData,
                playerList: playerList,
                bankerData: banker,
                bankerList: bankerList,
                roomSet: roomSet
            };

            utils.invokeCallback(cb, null, ret);
        }
        else {
            console.log(err);
            utils.invokeCallback(cb, err, null);
        }
    });
};

/**
 * 用户下线
 */
exp.kick = function (msg) {
    var room = this.getRoomById(msg.roomId);
    room.kickPlayer(msg);
};

/**
 * 获取房间对象
 */
exp.getRoomById = function (roomId) {
    var roomObj = roomData[roomId];
    return roomObj || null;
};

/**
 * 申请下注
 */
exp.bid = function (roomId, playerId, msg) {
    log('niuniu roomManager.bid caught >>>>>>>>>>>>>>>>>>>>');
    var ret = roomData[roomId].bid(playerId, msg);
    return ret;
};

/**
 * 申请上庄
 */
exp.applyBanker = function (msg, cb) {
    var roomId = msg.roomId;
    roomData[roomId].applyBanker(msg, cb);
};

/**
 * 申请下庄
 */
exp.cancelBanker = function (msg, cb) {
    var roomId = msg.roomId;
    roomData[roomId].cancelBanker(msg, cb);
};

/**
 * 申请插队上庄
 */
exp.cutInBanker = function (msg, cb) {
    var roomId = msg.roomId;
    roomData[roomId].cutInBanker(msg, cb);
};
